from django.http import HttpResponse
import json
import time
from django.utils import timezone
import gevent
from gevent import event,Greenlet
import os

fack=False

func_list=[]
def run():
    while True:
        for func_item in func_list:
            func_item()
        time.sleep(1)

Greenlet(run).start()


def long_link(span=None):
    def inn_func(func):
        if os.environ.get('long_link')=='unblock':
            return func
    
        def _func(*args,**kw):
            ev=event.Event()
            dc={'rt':None}
            before=time.time()
            def __func():
                dc['rt']=func(*args,**kw)
                if dc['rt']:
                    ev.set()
                after=time.time()
                if span and after-before > span:
                    ev.set()
                    
            func_list.append(__func)
            ev.wait()
            func_list.remove(__func)
            return dc['rt']
        return _func
    return inn_func

@long_link(span=10)
def test_func():
    if fack:
        return 'here is ok'

def block(request):
    now =timezone.now()
    ss = now.strftime('%Y-%m-%d %H:%M:%S')
    #ev=event.Event()
    #def ok():
        #if fack:
            #ev.set()
    #func_list.append(ok)
    #ev.wait()
    tt=test_func()
    
    now =timezone.now()
    after = now.strftime('%Y-%m-%d %H:%M:%S')  
    pid=os.getpid()
    return HttpResponse(json.dumps({'before':ss,'after':after,'pid':pid}),content_type="application/json")

def no_block(request):
    #if ev.is_set():
        #ev.clear()
    #else:
        #ev.set()
    global fack
    fack= not fack
    now =timezone.now()
    ss = now.strftime('%Y-%m-%d %H:%M:%S')
    pid=os.getpid()
    return HttpResponse(json.dumps({'now':ss,'pid':pid}),content_type="application/json")

def hello(request):
    pid=os.getpid()
    tm=time.time()
    return HttpResponse(json.dumps({'time':tm,'pid':pid}),content_type="application/json")